import {
  AfterViewInit,
  ChangeDetectionStrategy,
  Component,
  ElementRef,
  Input,
  OnChanges,
  SimpleChanges,
  TemplateRef,
  ViewEncapsulation,
} from '@angular/core';
import { InputBoolean, TypeUtils } from '../core/utils/api';
import { LvSizeSD } from '../core/types';
import { LvConfig } from '../core/config';
import { LvCardType } from './interface';

@Component({
  selector: 'lv-card',
  templateUrl: './card.component.html',
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    class: 'lv-card',
    '[class.lv-card-bordered]': "lvType!=='default' || lvBordered",
    '[class.lv-card-shadow]': "lvType==='shadow'",
    '[class.lv-card-hoverable]': 'lvHoverable',
    '[class.lv-card-disabled]': 'lvDisabled',
    '[class.lv-card-has-cover]': 'lvCover',
    '[class.lv-card-checked]': 'lvChecked',
    '[class.lv-card-small]': "lvSize==='small'",
  },
})
export class CardComponent implements AfterViewInit, OnChanges {
  @Input() lvCover: TemplateRef<void>;
  @Input() lvAction: TemplateRef<void>;
  @Input() lvShading: boolean | string;
  @Input() lvSize: LvSizeSD = 'default';
  @Input() lvType: LvCardType = 'default';
  @Input() @InputBoolean() lvChecked = false;
  @Input() @InputBoolean() lvLoading = false;
  /** @deprecated: 该属性功能使用lvType替代 */
  @Input() @InputBoolean() lvBordered = false;
  @Input() @InputBoolean() lvDisabled = false;
  @Input() lvTitle: string | TemplateRef<void>;
  @Input() lvExtra: string | TemplateRef<void>;
  @Input() @InputBoolean() lvHoverable = false;

  public typeUtils = TypeUtils;

  public assetsPrefixPath = LvConfig.assetsPrefixPath;

  constructor(private elementRef: ElementRef) {}

  ngAfterViewInit(): void {
    this.setShading();
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.lvShading) {
      this.setShading();
    }
  }

  setShading(): void {
    if (!this.lvShading) {
      return;
    }

    const src = this.typeUtils.isString(this.lvShading)
      ? this.lvShading
      : `${this.assetsPrefixPath}assets/webp/lv-card-bg.png`;
    this.elementRef.nativeElement.style.backgroundImage = `url(${src})`;
  }
}
